package com.smarth.zhizulian.http.interceptor;

import com.smarth.zhizulian.app.BaseConfig;
import com.smarth.zhizulian.utils.AESUtils;
import com.smarth.zhizulian.utils.GsonUtils;
import com.smarth.zhizulian.utils.KumaLog;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * Created by 18865 on 2018/1/18.
 */

public class SecurityInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        if (request.method() == "POST") {
            String myKey = UUID.randomUUID().toString().substring(0, 12);
            String url = request.url().toString().replace(BaseConfig.NetWork.BASE_URL, "/");
            String u = AESUtils.encrypt(url, myKey);
            KumaLog.http("real_url:" + url);
            FormBody.Builder formBodyBuilder = new FormBody.Builder()
                    .add("l", u)
                    .add("u", myKey);
            Request.Builder requestBuilder = new Request.Builder().url(BaseConfig.NetWork.BASE_ENCRYPTURL);

            RequestBody body = request.body();
            if (body instanceof FormBody) {
                FormBody formBody = (FormBody) body;
                Map<String, String> formMap = new HashMap<>();
                // 从 formBody 中拿到请求参数，放入 formMap 中
                for (int i = 0; i < formBody.size(); i++) {
                    formMap.put(formBody.name(i), formBody.value(i));
                }
                String jsonParams = GsonUtils.toJson(formMap);
//                String myKey = "1234567890123456";
                String p = AESUtils.encrypt(jsonParams, myKey);
                KumaLog.http("real_params" + jsonParams);
                formBodyBuilder.add("a", p);
            }
            Request newRequest = requestBuilder
                    .post(formBodyBuilder.build())
                    .build();
            return chain.proceed(newRequest);
        }
        return chain.proceed(request);
    }
}
